//数据驱动视图 通过数据遍历模板 渲染页面 捕获页面中各种事件 修改数据再次渲染页面！

class Myjs {
	//模板字符串
	template = (item) => {
		return `
				<tr>
					<td>
						<div class="custom-control custom-switch">
							<input type="checkbox" class="custom-control-input" 
								id="cb${item?.id}" 
								${item?.checked?'checked':null}
								my-check-change="${item?.id}"
							>
							<label class="custom-control-label" for="cb${item?.id}">${item?.checked?'已选':'未选'}</label>
						</div>
					</td>
					<td>${item?.id}</td>
					<td>${item?.name}</td>
					<td>${item?.num}</td>
					<td>￥${item?.price}</td>
					<td>￥${item?.num * item?.price}</td>
					<td>${item?.date}</td>
					<td>
						<a href="javascript:;" my-click="add('+',${item?.id})">增加</a>
						<a href="javascript:;" my-click="add('-',${item?.id})">减少</a>
						<a href="javascript:;" my-click="remove(${item?.id},)">删除</a>
					</td>
				</tr>
			`;
	}
	//增加的下一个id
	nextId = 3;
	//增加的下一个商品名
	nextName = "";
	//增加的下一个商品数量
	nextNum = 0;
	//增加的下一个商品价格
	nextPrice = 0.00;
	//接收到的模拟数据
	todos = [
		{id:1,name:"迪奥999色号口红",num:3,price:330.00,date:"2023-01-11 08:30:00",checked:true},
		{id:2,name:"兰蔻196色号口红",num:2,price:320.00,date:"2023-01-11 08:30:00",checked:false}
	];
	//商品的总金额
	totalPrice = 0.00;
	//增加或减少数量
	add(flag,id) {
		if (flag == "'-'") {
			if (this.todos.some(item=>{
				if (item.id==id&&item.num<=0) {
					return true;
				}
			})) {
				return;
			}
			this.todos.some(item=>{
				if (item.id == id) {
					item.num--;
					return true;
				}
			})
		} else{
			this.todos.some(item=>{
				if (item.id == id) {
					item.num++;
					return true;
				}
			})
		}
		this.show();
	}
	//删除功能
	remove(id){
		if (confirm("确定删除吗？")) {
			this.todos = this.todos.filter(item=>item.id!=id)
		}
		this.show();
	}
	//计算总金额
	sumPrice() {
		return this.todos
		.filter(item => item.checked)
		.reduce((total, item) => (total += item.price * item.num), 0)
		.toFixed(2);
	}
	//修改单个商品选择状态
	changeCheck(id){
		this.todos.some(item=>{
			if (item.id == id) {
				item.checked = !item.checked;
				return true;
			}
		})
		this.changeCheckAllState(this.todos.every(item => item.checked))
		this.show();
	}
	//修改全选取按钮的状态
	changeCheckAllState(flag){
		if (flag) {
			document.getElementById("cb0").checked = true;
		}else{
			document.getElementById("cb0").checked = false;
		}
	}
	//点击全选按钮 修改每一个商品的选择状态
	changeEveryChenck(flag){
		this.todos.forEach(item => (item.checked = flag))
		this.show();
	}
	//添加商品
	addProduct(){
		this.nextName = document.querySelector("[my-name]").value;
		this.nextNum = document.querySelector("[my-number]").value;
		this.nextPrice = document.querySelector("[my-price]").value;
		console.log(this.nextName,this.nextNum,this.nextPrice);
		if (this.nextName == "" || this.nextNum == 0 || this.nextPrice == 0) {
			alert("商品名，数量，价格均不可为空！");
			this.show();
			return;
		}
		this.todos = [
			...this.todos,
			{
				id:this.nextId,
				name:this.nextName,
				num:this.nextNum*1,
				price:this.nextPrice*1,
				date:dayjs().format('YYYY-MM-DD HH:mm:ss'),
				checked:true
			}
		]
		this.nextId++;
		this.nextName = "";
		this.nextNum = 0;
		this.nextPrice = 0;
		document.querySelector("[my-name]").value = ""
		document.querySelector("[my-number]").value = 0;
		document.querySelector("[my-price]").value = 0.00;
		this.show();
	}
	//页面整体的监听事件
	listening(){
		//捕获my-click点击事件
		let myClickAction = () => {
			let myClicks = document.querySelectorAll("[my-click]");
			for (let i = 0; i < myClicks.length; i++) {
				myClicks[i].addEventListener("click",e=>{
					let str = e.target.getAttribute("my-click");
					//分组查询
					const reg = /(.*)\((.*),(.*)\)/g;
					let res = reg.exec(str);
					//绑定add添加事件
					if (res[1] == "add") {
						this.add(res[2],res[3])
					}
					//绑定remove事件
					if (res[1] == "remove") {
						this.remove(res[2])
					}
				},{ once: true })
			}
		}
		myClickAction();
		
		//捕获my-text文本插值实践
		let myTestAction = () => {
			let myTexts = document.querySelectorAll("[my-text]");
			for (let i = 0; i < myTexts.length; i++) {
				if ((myTexts[i].attributes)[0].value == "totalPrice") {
					myTexts[i].innerHTML = this.sumPrice();
				}
			}
		}
		myTestAction();
		
		//捕获 my-check-change 修改数据中已选按钮的状态
		let myCheckChange = () => {
			let myChecks = document.querySelectorAll("[my-check-change]");
			for (let i = 0; i < myChecks.length; i++) {
				myChecks[i].addEventListener("change",e=>{
					this.changeCheck(myChecks[i].getAttribute("my-check-change"))
				},{ once: true })
			}
		}
		myCheckChange();
		
		//捕获 id为cb0 input全选按钮
		let myCheckAllAction = () => {
			document.getElementById("cb0").addEventListener("change",e=>{
				this.changeEveryChenck(e.target.checked)
			},{ once: true })
		}
		myCheckAllAction();
		//捕获 增加商品submint按钮
		let addProductSubmintAction = () => {
			document.querySelector("[my-submit]").addEventListener("click",e=>{
				e.preventDefault();
				
				this.addProduct();
			},{ once: true })
		}
		addProductSubmintAction();
	}
	//用于显示页面的内容
	show(){
		let str = "";
		this.todos.forEach(todo=>{
			str += this.template(todo);
		})
		//渲染遍历好的模板字符串
		document.getElementById("mytbody").innerHTML = str;
		//绑定监听
		this.listening();
	}
	//整体的启动函数
	star(){
		this.show();
	}
}
export default Myjs;